import { ref, onMounted } from 'vue'

export function useTheme() {
  const currentTheme = ref(localStorage.getItem('app-theme') || 'light')
  
  const setTheme = (theme) => {
    currentTheme.value = theme
    document.documentElement.setAttribute('data-theme', theme)
    localStorage.setItem('app-theme', theme)
    
    // 处理Element Plus暗黑模式
    if (theme === 'dark') {
      document.documentElement.classList.add('dark')
      import('element-plus/theme-chalk/dark/css-vars.css')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
  
  const toggleTheme = () => {
    setTheme(currentTheme.value === 'light' ? 'dark' : 'light')
  }
  
  // 自动检测系统主题
  const detectSystemTheme = () => {
    const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    return isDark ? 'dark' : 'light'
  }
  
  // 初始化主题
  onMounted(() => {
    if (!localStorage.getItem('app-theme')) {
      setTheme(detectSystemTheme())
    } else {
      setTheme(currentTheme.value)
    }
    
    // 监听系统主题变化
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
      if (!localStorage.getItem('app-theme')) {
        setTheme(e.matches ? 'dark' : 'light')
      }
    })
  })
  
  return { currentTheme, setTheme, toggleTheme }
}